package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.FreeMarkerService;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.file.service.MinioService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class FreeMarkerServiceImpl implements FreeMarkerService {

    @Autowired
    private Configuration configuration;
    @Autowired
    private MinioService minioService;
    @Lazy
    @Autowired
    private ApArticleService apArticleService;

    @Async
    @Override
    public void createHtml(Long articleId, String content) {
        log.info("------开始生成页面");
//        获取模板对象
        try {
            Template template = configuration.getTemplate("article.ftl");
//        准备动态数据
            Map<String,Object> map = new HashMap<>();
            map.put("content", JSONArray.parseArray(content));
//            生成静态页面
            StringWriter stringWriter = new StringWriter();
            template.process(map,stringWriter);
//            构造输入流
            InputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
//            声名页面的名字，不能重复，使用文章id
            String fileName = articleId+".html";
            //        存入minio
            String htmlUrl = minioService.uploadHtmlFile("",fileName,inputStream);
            if(StringUtils.isBlank(htmlUrl)){
                log.error("静态页面的url为空");
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }
//            保存ap_article表的static_url字段
            ApArticle apArticle = new ApArticle();
            apArticle.setId(articleId);
            apArticle.setStaticUrl(htmlUrl);
            apArticleService.updateById(apArticle);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
